package com.central.gateway.filter;

import com.central.common.constant.ExtendConstant;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @program: central-platform
 * @author: lishuai
 * @create: 2022-02-08 18:15
 * 控制后端服务器的访问必须经过网关才可以
 */
@Component
@Order(0)
public class GatewayBackendAccessRequestFilter  implements GlobalFilter {
    //在请求经过网关时添加额外的Header，为了方便这里直接设置成固定值
    //private final static String backend_access_token = "backend_access_token";
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        byte[] token = Base64Utils.encode(ExtendConstant.backend_access_token.getBytes());
        String[] headerValues = {new String(token)};
        ServerHttpRequest build = exchange.getRequest()
                .mutate()
                .header(ExtendConstant.backend_access_token, headerValues)
                .build();

        ServerWebExchange newExchange = exchange.mutate().request(build).build();
        return chain.filter(newExchange);
    }
}
